﻿//-----------------------------------------------------------------------
// <copyright file="MapperAttribute.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.Core.Infrastucture.Mapper.Impl
{
    using System;
    using System.Web.Mvc;

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class MapperAttribute : ActionFilterAttribute
    {

        private readonly Type sourceType;
        private readonly Type destType;

        public IMapper Mapper { get; set; }

        public MapperAttribute(Type sourceType, Type destType)
        {
            this.sourceType = sourceType;
            this.destType = destType;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (typeof(JsonResult).IsAssignableFrom(filterContext.Result.GetType()))
            {
                var result = (JsonResult)filterContext.Result;
                result.Data = AutoMapper.Mapper.Map(result.Data, this.sourceType, this.destType);
            }
            else
            {
                var model = filterContext.Controller.ViewData.Model;
                object viewModel = AutoMapper.Mapper.Map(model, this.sourceType, this.destType);
                filterContext.Controller.ViewData.Model = viewModel;
            }
        }

        public Type SourceType
        {
            get { return this.sourceType; }
        }

        public Type DestType
        {
            get { return this.destType; }
        }
    }
}